package cn.test.spring.websocket;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.websocket.Session;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * @author Han
 */
@Component
public class MyHandler extends TextWebSocketHandler{
	private static Map<String, WebSocketSession> map = new HashMap<String, WebSocketSession>();
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		System.out.println("Received: " + message);
		Iterator it = map.values().iterator();
		System.out.println(map.size());
		while (it.hasNext()) {
			WebSocketSession tmp = (WebSocketSession) it.next();
			tmp.sendMessage(new TextMessage("呵呵呵".getBytes()));
		}
	}
	
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		super.afterConnectionClosed(session, status);
		map.remove(session.getId());
		
	}
	
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		super.afterConnectionEstablished(session);
		map.put(session.getId(), session);
	}
}
